<template>
  <view>
    <u-sticky>
      <u-navbar back-text=" " title="签证" :background="background" title-color="#ffffff" :custom-back="customBack" back-icon-color="#ffffff" ref="navbar" title-size="36"></u-navbar>
      <xmInfo
        :projectno="itemContent.projectno"
        :projectname="itemContent.projectname"
        ref="xmInfo"
        class="u-sticky"
      ></xmInfo>
    </u-sticky>
      <scroll-view
        scroll-y="true"
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :scrolltolower-enabled="true"
        :refresher-triggered="triggered"
        @refresherrefresh="refresherrefresh"
        class="scroll-view-class"
        :style="{ height: computedScrollViewHeight }"
      >
      <view
        class="scroll-content"
        ref="scrollContent"
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
        :style="{ height: computedScrollViewHeight  }"
      >
      <view class="cu-item shadow" v-for="(item, index) in list" :key="item.id">
          <view class="cu-form-group" style="display: flex; justify-content: space-between">
            <view style=" display: inline-block;padding: 5px;background: #3E97B0;color: #fff;width: 40px;text-align: center;font-style: italic;font-weight: bold">
              {{ index + 1 }}
            </view>
			<view class="text-xl text-bold">{{ item.createDate }}</view>
          </view>
        <!--  <view class="cu-form-group">
            <view class="text-xl text-bold">创建时间</view>
            <view class="text-xl text-bold">{{ item.createDate }}</view>
          </view> -->
         
          <view class="cu-form-group">
            <view class="title">签证类型</view>
            <view>{{ item.istemporary == 1 ? "正式签证" : "临时签证" }}</view>
          </view>
		  <view class="cu-form-group">
		    <view class="title">描述</view>
		    <view>{{ item.describe || '' }}</view>
		  </view>
          <view class="cu-form-group" style="min-height: 0"></view>
          <view class="cu-bar bg-white">
            <view class="action text-black">签证图片</view>
          </view>
          <view class="cu-form-group">
            <js-uploadfile  v-model="item.dataMap"  :biz-key="item.id"   biz-type="PmVisaQz_image" :deletable="false" customBtn="false"></js-uploadfile>
          </view>
          <view class="cu-form-group" style="min-height: 0"></view>
          <view class="cu-bar bg-white">
            <view class="action text-black">现场图片</view>
          </view>
          <view class="cu-form-group">
            <js-uploadfile  v-model="item.dataMap"  :biz-key="item.id"   biz-type="PmVisaXc_image" :deletable="false" customBtn="false"></js-uploadfile>
          </view>
		  <view class="cu-form-group">
		    <view class="title">上传人</view>
		    <view>{{ item.operator }}</view>
		  </view>
          <view class="cu-form-group" style="color:#3E97B0 ;"  @click="add(item.id)">
            <view class="content-footer-right">查看详情</view>
            <u-icon name="arrow-right"></u-icon>
          </view>
        </view>
        
        <view v-if="list.length" class="loadmore">
          <u-loadmore :status="loadStatus"></u-loadmore>
        </view>
        <u-empty v-if="!list.length" style="height: 100%;"></u-empty>
      </view>
      </scroll-view>
      <view class="btn-group cu-bar foot" v-if="addflag">
        <button :disabled="projStatus=='5' || projStatus=='6' || projStatus=='7'?true:false" class="cu-btn bg-green shadow-blur" @tap="add()">
          <text class="cuIcon-add"></text>创建
        </button>
      </view>
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: { xmInfo},
  data() {
    return {
      background:{
        backgroundColor: '#3E97B0',
      },
      modalNameDetail: null,
      applyFile: [],
      showAddDetail: false,
      list: [],
      itemContent: {},
      query: {
        pageNo: 1,
        pageSize: 20,
        projInfo:{
            projectno: "",
            projectname: "",
        }
        // orderBy: "a.create_date desc",
      },
      loadStatus: "loadmore",
      triggered: false,
      addflag:hasPermission('app:btn:add:xianchangqianzheng'),
      scrollViewHeight: 0,
      headerHeight: 0,
	  projStatus:this.$store.state.auth.projStatus,
    };
  },
  onShow() {
    this.query.pageNo = 1;
    this.loadData();
  },
  onLoad(e) {
    if (typeof e.item !== "undefined") {
      try {
        this.itemContent = JSON.parse(e.item);
        console.log(this.itemContent);
        this.query.projInfo.projectno = this.itemContent.projectno;
        this.query.projInfo.projectname = this.itemContent.projectname;
        console.log(this.query);

        // this.loadData();
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }
  },
  mounted() {
    this.$refs.xmInfo.$on('child-mounted-done', () => {
      this.calculateScrollViewHeight();
    });
  },
  computed: {
    computedScrollViewHeight() {
      return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
    },
  },

  methods: {
    customBack(){
      // 跳转到工作台页面
      // uni.navigateTo({
      //   url: "/pages/zfgs/index/index/index?item=" + JSON.stringify(this.itemContent),
      // });
	  uni.navigateBack({
	    delta: 1,
	  });
    },
    async calculateScrollViewHeight() {
      try {
          // 等待头部高度计算完成
          await new Promise((resolve) => {
            this.$nextTick(() => {
              this.headerHeight = this.$refs.xmInfo.$refs['u-sticky'].height + this.$refs.xmInfo.$refs['u-sticky'].h5NavHeight + this.$refs.navbar.navbarHeight;
              resolve();
            });
          });
          // 计算tabBar高度
          if(this.addflag){
            this.tabBarHeight = 90; // 假设tabbar高度为50px，实际应根据实际情况获取
          }else{
            this.tabBarHeight = 0;
          }

          // 获取屏幕高度
          const systemInfo = uni.getSystemInfoSync();
          const screenHeight = systemInfo.windowHeight;

          // 计算scroll-view高度
          this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
      } catch (error) {
        console.error('Error while calculating ScrollView height:', error);
      }

    },
    loadMore() {
      this.loadStatus = "loading";
      console.log("加载更多");
      setTimeout(() => {
        this.query.pageNo += 1;
        this.loadData("add");
      }, 100);
    },
    loadData(type) {
      // 循环10次重复赋值
      this.$u.api.zfgs.visaPmVisaListData(this.query).then((res) => {
        if (res.list.length >= 0) {
          // this.xmList = res.list
          if (res.list.length < 20 || res.list.length == 0) {
            this.loadStatus = "nomore";
            var data = res.list;
            this.list = data;
          }else{
            var data = res.list;
            if (type == "add") {
              for (var i = 0; i < data.length; i++) {
                this.list.push(data[i]);
              }
            } else {
              this.list = data;
            }
          }

        }
      });
    },
    async refresherrefresh() {
      this.triggered = true;
      this.query.pageNo = 1;
      await this.loadData();
      const scrollTop = 0
      uni.pageScrollTo({
            scrollTop,
            duration: 0,
      });    
      setTimeout(() => {
        this.triggered = false;
      }, 500);
      // this.triggered = false;
    },
    add(id) {
      
      if (!!id) {
        uni.navigateTo({
          url: "/pages/zfgs/design/visa/pmVisa/form?id=" + id,
        });
      } else {
        const xm = {
                'projInfo.projectno': this.itemContent.projectno,
                'projInfo.projectname': this.itemContent.projectname,
            }
        uni.navigateTo({
          url: "/pages/zfgs/design/visa/pmVisa/form?xm=" + JSON.stringify(xm),
        });
      }
    },
    ViewImage(imageList, e) {
      // 阻止冒泡
      const urls = imageList.map((v) => v.url);
      e.stopPropagation();
      uni.previewImage({
        urls: urls,
        current: e.currentTarget.dataset.url,
      });
    },
    addDetail(applyFile) {
      this.showAddDetail = true;
      this.modalNameDetail = "bottomModal";
      this.applyFile = applyFile;
      console.log(applyFile, "applyFile", this.applyFile);
    },
    modalNameDetailEmit(e) {
      this.modalNameDetail = e;
      this.showAddDetail = false;
    },
  },
  beforeDestroy() {
    // 清理事件监听器
    try {
       this.$refs.xmInfo.$off('child-mounted-done');
     } catch (e) {
       console.log('Error while unbinding event:', e);
     }
  },
};
</script>
<style lang="scss" scoped>
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  background: #fff;
  min-height: 80px;
}
.cu-item {
  flex-wrap: wrap;
  padding: 15px !important;
}
.title {
  flex-shrink: 0;
}
.grid-square {
  margin-bottom: 0 !important;
}
.cuIcon-image {
  width: 40px;
  height: 40px;
}
</style>